const client = require('../client')
const print = require('./print')

const match_all = (index, params) => {
  return client.search({
    index,
    body: {
      query: {match_all: {}}
    }
  })
}

const query = (index, params) => {
  return client.search({
    index,
    body: JSON.parse(params)
  })
}

const script = (index, params) => {
  return client.search({
    index,
    body: {
      query: {
        function_score: {
          script_score: {
            script: {
              lang: 'painless',
              source: params[0]
            }
          }
        }
      }
    }
  })
}

const subs = {match_all, query, script}

module.exports = (sub, index, params) => {
  if(!subs[sub]) {
    console.log(`${sub} is not supported in search module.` )
    process.exit(1)
  }
  subs[sub](index, params).then(print)
}
